package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FillertypeService")
@Transactional

public class FillertypeServiceImpl extends CmiEmaService implements FillertypeService {
	public FillertypeServiceImpl() {
	}

	@Transactional
	public Fillertype saveFillertype(Fillertype fillertype) {
		Set<Filler> existingFillersForFillertype = new HashSet<Filler>();
		Set<Hazard> existingHazardsForHazard = new HashSet<Hazard>();

		Set<Filler> selectedFillersForFillertype = fillertype.getFillersForFillertype();
		Set<Hazard> selectedHazardsForHazard = fillertype.getHazardsForFillertype();

		if (fillertype.getId() == null) {

			Fillertype existingFillertype = fillertypeDAO.findFillertypeByPhysicalPrimaryKey(fillertype.getName(),
					fillertype.getParent());

			if (isEquals(fillertype, existingFillertype)) {
				return existingFillertype;
			}

			fillertype = fillertypeDAO.store(fillertype);
			fillertypeDAO.flush();

			for (Filler relatedFiller : selectedFillersForFillertype) {
				relatedFiller.setFillertype(fillertype);
				fillerDAO.store(relatedFiller);
			}

			for (Hazard relatedHazard : selectedHazardsForHazard) {
				relatedHazard.getFillertypesForHazard().add(fillertype);
				hazardDAO.store(relatedHazard);
			}
		} else {
			Fillertype existingFillertype = fillertypeDAO.findFillertypeByPrimaryKey(fillertype.getId());

			existingFillersForFillertype = existingFillertype.getFillersForFillertype();
			existingHazardsForHazard = existingFillertype.getHazardsForFillertype();

			Set<Filler> prepareDeleteFillersForFillertype = new HashSet<Filler>();
			Set<Filler> prepareAddFillersForFillertype = new HashSet<Filler>();

			prepareDeleteFillersForFillertype.addAll(selectedFillersForFillertype);
			prepareDeleteFillersForFillertype.addAll(existingFillersForFillertype);

			prepareAddFillersForFillertype.addAll(selectedFillersForFillertype);
			prepareAddFillersForFillertype.addAll(existingFillersForFillertype);

			prepareDeleteFillersForFillertype.removeAll(selectedFillersForFillertype);
			prepareAddFillersForFillertype.removeAll(existingFillersForFillertype);

			for (Filler relatedFiller : prepareAddFillersForFillertype) {
				relatedFiller.setFillertype(fillertype);
				fillerDAO.store(relatedFiller);
			}

			for (Filler relatedFiller : prepareDeleteFillersForFillertype) {
				relatedFiller.setFillertype(null);
				fillerDAO.store(relatedFiller);
			}
			Set<Hazard> prepareDeleteHazardsForHazard = new HashSet<Hazard>();
			Set<Hazard> prepareAddHazardsForHazard = new HashSet<Hazard>();

			prepareDeleteHazardsForHazard.addAll(selectedHazardsForHazard);
			prepareDeleteHazardsForHazard.addAll(existingHazardsForHazard);

			prepareAddHazardsForHazard.addAll(selectedHazardsForHazard);
			prepareAddHazardsForHazard.addAll(existingHazardsForHazard);

			prepareDeleteHazardsForHazard.removeAll(selectedHazardsForHazard);
			prepareAddHazardsForHazard.removeAll(existingHazardsForHazard);

			for (Hazard relatedHazard : prepareAddHazardsForHazard) {

				relatedHazard.getFillertypesForHazard().add(existingFillertype);
				hazardDAO.store(relatedHazard);
			}

			for (Hazard relatedHazard : prepareDeleteHazardsForHazard) {

				relatedHazard.getFillertypesForHazard().remove(existingFillertype);
				hazardDAO.store(relatedHazard);
			}
			fillertype = fillertypeDAO.store(fillertype);
			fillertypeDAO.flush();
		}

		fillerDAO.flush();
		hazardDAO.flush();
		return fillertype;
	}

	public void deleteFillertype(Fillertype fillertype) {
		fillertypeDAO.remove(fillertype);
		fillertypeDAO.flush();
	}

	@Transactional
	public void deleteFillertypes(Set<Integer> deleteFillertypesId) {
		Query query = fillertypeDAO.createNamedQuery("deleteFillertypesById", -1, -1);
		query.setParameter(1, deleteFillertypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Fillertype> loadFillertypes() {
		return fillertypeDAO.findAllFillertypes();

	}

	@Transactional
	public Set<Fillertype> loadReferenceFillertypes(Set<Fillertype> fillertypes) {
		Iterator<Fillertype> fillertypesIterator = fillertypes.iterator();
		Set<Fillertype> referencedFillertypes = new HashSet<>();
		while (fillertypesIterator.hasNext()) {
			Fillertype currentFillertype = fillertypesIterator.next();

			if (!currentFillertype.getFillersForFillertype().isEmpty()) {
				referencedFillertypes.add(currentFillertype);
				continue;
			}

			if (!currentFillertype.getHazardsForFillertype().isEmpty()) {
				referencedFillertypes.add(currentFillertype);
				continue;
			}
		}
		return referencedFillertypes;
	}

	public Set<Fillertype> loadFillertypesByIdSet(Set<Integer> fillertypeIdSet) {

		Iterator<Integer> fillertypeIdIterator = fillertypeIdSet.iterator();
		Set<Fillertype> fillertypeSet = new HashSet<>();
		while (fillertypeIdIterator.hasNext()) {
			Integer id = fillertypeIdIterator.next();
			Fillertype currentFillertype = fillertypeDAO.findFillertypeById(id);
			fillertypeSet.add(currentFillertype);
		}
		return fillertypeSet;
	}

	@Transactional
	public List<Fillertype> findAllFillertypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Fillertype>(fillertypeDAO.findAllFillertypes(startResult, maxRows));
	}

	@Transactional
	public Fillertype findFillertypeByPrimaryKey(Integer id) {
		return fillertypeDAO.findFillertypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countFillertypes() {
		return ((Long) fillertypeDAO.createQuerySingleResult("select count(o) from Fillertype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countFillertypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Fillertype.class);
		return ((Long) fillertypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFillertypesByName(String queryName) {
		Query query = fillertypeDAO.createNamedQuery("countFillertypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFillertypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Fillertype.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFillertypeObjectReferencedSet(Fillertype fillertype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> fillersIds = new HashSet<Integer>();
		for (Filler obj : fillertype.getFillersForFillertype()) {

			fillersIds.add(obj.getId());
		}
		objectReferencedSetMap.put("fillersIds", fillersIds);
		Set<Integer> hazardsIds = new HashSet<Integer>();
		for (Hazard hazard : fillertype.getHazardsForFillertype()) {
			hazardsIds.add(hazard.getId());
		}
		objectReferencedSetMap.put("hazardsIds", hazardsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFillertypeClassReferencedSet(Fillertype fillertype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("fillers", fillerDAO.findAllFillers());
		classReferencedSetMap.put("hazards", hazardDAO.findAllHazards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Fillertype fillertype, Object obj) {
		if (obj == fillertype)
			return true;
		if (!(obj instanceof Fillertype))
			return false;
		Fillertype comparedFillertype = (Fillertype) obj;
		if (!CheckPropertyEqual(fillertype.getName(), comparedFillertype.getName())) {
			return false;
		}
		if (!CheckPropertyEqual(fillertype.getParent(), comparedFillertype.getParent())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

